package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.StrategyCatalog;
import cn.wolfcode.luowowo.article.domain.ViewpointComment;
import cn.wolfcode.luowowo.article.domain.*;
import cn.wolfcode.luowowo.article.service.*;
import cn.wolfcode.luowowo.cache.service.IViewpointStatsCacheService;
import cn.wolfcode.luowowo.cache.vo.ViewpointStats;
import cn.wolfcode.luowowo.comment.domain.ViewpointRefComment;
import cn.wolfcode.luowowo.comment.service.IViewpointRefCommentService;
import cn.wolfcode.luowowo.common.query.DestinationQueryObject;
import cn.wolfcode.luowowo.common.query.TravelQueryObject;
import cn.wolfcode.luowowo.common.query.ViewpointCommentQueryObject;
import cn.wolfcode.luowowo.common.query.ViewpointQueryObject;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.LoginUser;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
@RequestMapping("/destination")
public class DestinationController {
    @Reference
    private IRegionService regionService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IRecommedService recommedService;
    @Reference
    private IStrategyThemeService strategyThemeService;

    @RequestMapping("")
    public String index(Model model) {
        //显示热门地区de
        model.addAttribute("hotRegions", regionService.listHotRegions());
        //显示月份和月份对应地区
        List<Recommend> recommends = recommedService.selecetAll();


        //主题头一月数据
        Recommend remove = recommends.remove(0);
        List<Destination> removeList = destinationService.listDestByRecmmendId(remove.getRefIds());
        List<Destination> upDest = removeList.subList(0, removeList.size() / 2);
        List<Destination> downDest = removeList.subList(removeList.size() / 2, removeList.size());
        model.addAttribute("upDest", upDest);
        model.addAttribute("downDest", downDest);

        List<Destination> destinations = new ArrayList<>();
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Recommend recommend : recommends) {
            Map<String, Object> map = new HashMap<>();
            //根据推荐查询目的地
            destinations = destinationService.listDestByRecmmendId(recommend.getRefIds());
            //上面
            List<Destination> upDests = destinations.subList(0, destinations.size() / 2);
            //下面
            List<Destination> downDests = destinations.subList(destinations.size() / 2, destinations.size());
            map.put("upDests", upDests);
            map.put("downDests", downDests);
            mapList.add(map);
        }
        model.addAttribute("recommends", recommends);
        model.addAttribute("mapList", mapList);


        //连表查询主题和攻略
      /*  List<StrategyDetail> details = strategyDetailService.list();

        model.addAttribute("details",details);*/
        //查询所有主题,再通过主题id查询一个攻略
        List<StrategyTheme> themes = strategyThemeService.list();
        List<StrategyDetail> details = new ArrayList<>();
        for (StrategyTheme theme : themes) {
            StrategyDetail detail = strategyDetailService.selectByThemeIdOne(theme.getId());
            if (detail != null) {
                detail.setTheme(theme);
                details.add(detail);
            }
        }
        model.addAttribute("details", details);
        return "destination/index";
    }

    /**
     * 国内查找省份,其他查询查找国家
     * @param regionId
     * @return
     */
    @RequestMapping("/listHotDestByRegionId")
    public String listHotDestByRegionId(@ModelAttribute("regionId") Long regionId, Model model){
        List<Destination> list = destinationService.listHotDestByRegionId(regionId);
        List<Destination> leftDests = list.subList(0, list.size() / 2);
        List<Destination> rightDests = list.subList(list.size() / 2, list.size());
        model.addAttribute("leftDests",leftDests);
        model.addAttribute("rightDests",rightDests);
        return "destination/hotdestTpl";
    }

    @Reference
    private IStrategyCatalogService strategyCatalogService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @RequestMapping("/guide")
    public String guide(Long id,Model model){
        List<Destination> toasts = destinationService.listToasts(id);
        model.addAttribute("catalogs",strategyCatalogService.listCatalogByDestId(id));
        model.addAttribute("toasts",toasts);
        model.addAttribute("dest",toasts.remove(toasts.size()-1));
        model.addAttribute("strategyDetails",strategyDetailService.selectByDestId(id));

        return "destination/guide";
    }


    @RequestMapping("surveyPage")
    public String surveyPage(@ModelAttribute("qo")DestinationQueryObject qo,Model model){
        //toasts
        List<Destination> toasts = destinationService.listToasts(qo.getDestId());
        model.addAttribute("toasts",toasts);
        //dest
        model.addAttribute("dest",toasts.remove(toasts.size()-1));
        return "destination/survey";
    }


    @RequestMapping("survey")
    public String survey(@ModelAttribute("qo")DestinationQueryObject qo,Model model){
        //catalogs
        List<StrategyCatalog> catalogs = strategyCatalogService.listCatalogByDestId(qo.getDestId());
        StrategyCatalog catalog = new StrategyCatalog();

        //catalog
        for (StrategyCatalog strategyCatalog : catalogs) {
            if (strategyCatalog.getId().equals(qo.getCatalogId())){
                catalog = strategyCatalog;
                break;
            }
        }
        //detail
        model.addAttribute("detail",catalog.getDetails().get(0));
        model.addAttribute("catalogs",catalogs);
        model.addAttribute("catalog",catalog);
        return "destination/surveyTpl";
    }


    @Reference
    private ITravelService travelService;
    /**
     * 游记高级查询
     * @param qo
     * @param model
     * @return
     */
    @RequestMapping("travels")
    public String travels(@ModelAttribute("qo")TravelQueryObject qo,Model model){
        PageInfo pageInfo = travelService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "destination/travelTpl";
    }

    @RequestMapping("travelFilter")
    public String travelFilter(Long themeId, Model model) {
        //通过主题id查询出所有的攻略
        List<StrategyDetail> details = strategyDetailService.selectByThemeId(themeId);
        if (details != null) {
            for (StrategyDetail detail : details) {
                List<StrategyDetail> strategyDetails = strategyDetailService.selectByDestId(detail.getDest().getId());
                if (strategyDetails != null) {
                    detail.setStrategyDetails(strategyDetails);
                }
            }
            model.addAttribute("details", details);
        }

        //查询月份
        List<Recommend> recommends = recommedService.selecetAll();
        List<Recommend> month = recommends.subList(0, 12);
        model.addAttribute("month", month);
        //查询节日
        List<Recommend> festival = recommends.subList(12, 14);
        model.addAttribute("festival", festival);
        //查询天数
        List<Recommend> days = recommends.subList(14, 18);
        model.addAttribute("days", days);
        //查询主题
        List<StrategyTheme> themes = strategyThemeService.list();
        model.addAttribute("themes", themes);
        return "destination/destFilter";
    }


    @RequestMapping("travelFilterTpl")
    public String travelFilterTpl(Long themeId, Model model, Long monthId, Long themesId, Long daysId) {
        //通过id查出推荐目的地
        Long[] refIds = new Long[]{};
        if (monthId != null && themesId != null && daysId != null) {
            if (monthId != -1) {
                Recommend month = recommedService.selectById(monthId);
                refIds = month.getRefIds();
            }
            if (themesId != -1) {
                themeId=themesId;
            }else {
                themeId=null;
            }
            if (daysId != -1) {
                Recommend days = recommedService.selectById(daysId);
                refIds = getSet(refIds, days.getRefIds());
            }
        }

        if (refIds.length < 1) {
            refIds = new Long[]{-1L};
        }
        if (monthId==-1 && daysId==-1){
            refIds=null;
        }


        //通过主题id查询出所有的攻略
        List<StrategyDetail> details = strategyDetailService.selectByCondition(themeId, refIds);

        if (details != null) {
            for (StrategyDetail detail : details) {
                List<StrategyDetail> strategyDetails = strategyDetailService.selectByDestId(detail.getDest().getId());
                if (strategyDetails != null) {
                    detail.setStrategyDetails(strategyDetails);
                }
            }
            model.addAttribute("details", details);
        }
        return "destination/destFilterTpl";
    }

    //获取两个数组交集
    private Long[] getSet(Long[] one, Long[] two) {
        List<Long> rs = new ArrayList<Long>();
        // 将较长的数组转换为set
        Set<Long> set = new HashSet<Long>(Arrays.asList(one.length > two.length ? one : two));
        // 遍历较短的数组，实现最少循环
        for (Long i : one.length > two.length ? two : one) {
            if (set.contains(i)) {
                rs.add(i);
            }
        }
        Long[] arr = {};
        return rs.toArray(arr);
    }

    @Reference
    private IViewpointService viewpointService;
    //景点文章列表
    @RequestMapping("viewpointlist")
    public String viewpointlist( Model model,@ModelAttribute("qo") ViewpointQueryObject qo){
        List<Destination> toasts = destinationService.listToasts(qo.getDestId());
        toasts.remove(0);
        model.addAttribute("toasts",toasts);
        //dest
        model.addAttribute("dest",toasts.remove(toasts.size()-1));
        //地区景点概况
        model.addAttribute("attr",destinationService.getAttractionByDestId(qo.getDestId()));
        //推荐必游的5个景点
        model.addAttribute("commendVps",viewpointService.listCommendViewpointTop5(qo.getDestId()));
        //热门景点
        model.addAttribute("hotVps",viewpointService.listHotViewpoint(qo.getDestId()));
        //地区所有景点
        model.addAttribute("pageInfo",viewpointService.query(qo));
        model.addAttribute("tags",viewpointService.listTagsByDestId(qo.getDestId()));
        return "destination/viewpointlist";
    }



    //景点详情文章
    @RequestMapping("viewpointdetail")
    public String viewpointdetail(@ModelAttribute("qo") ViewpointCommentQueryObject qo,@LoginUser UserInfo userInfo, Model model){

        if(userInfo != null){
            //是否收藏过该景点
            boolean isfavor = viewpointStatsCacheService.isFavor(qo.getPointId(), userInfo.getId());
            model.addAttribute("isfavor",isfavor);
            //是否去过该景点
            boolean iscame = viewpointStatsCacheService.isCame(qo.getPointId(), userInfo.getId());
            model.addAttribute("iscame",iscame);
        }
        //吐司
        List<Destination> toasts = destinationService.listToasts(qo.getDestId());
        toasts.remove(0);
        model.addAttribute("toasts",toasts);
        //dest
        model.addAttribute("dest",toasts.remove(toasts.size()-1));
        //景点详情
        model.addAttribute("vp",viewpointService.get(qo.getPointId()));

        model.addAttribute("pageInfo",viewpointCommentService.query(qo));

        ViewpointStats vo = viewpointStatsCacheService.getViewpointStats(qo.getPointId());
        model.addAttribute("replynum",vo.getReplynum());
        //有图数量
        model.addAttribute("hasImageNum",viewpointCommentService.hasImageNum(qo.getPointId()));
        //好评数量
        model.addAttribute("GoodNum",viewpointCommentService.goodNum(qo.getPointId()));
        //中评数量
        model.addAttribute("AverageNum",viewpointCommentService.averageNum(qo.getPointId()));
        //差评数量
        model.addAttribute("BadNum",viewpointCommentService.badNum(qo.getPointId()));
        return "destination/viewpointdetail";
    }

    @RequestMapping("/hasthumbup")
    @ResponseBody
    public Object hasthumbup(Long viewpointId ,@LoginUser UserInfo userInfo){
        //给景点的哪些评论点过赞
        List<Long> commentIds = viewpointStatsCacheService.isThumbup(viewpointId, userInfo.getId());
        return commentIds;
    }

    @Reference
    private IViewpointCommentService viewpointCommentService;

    //添加景点点评
    @RequestMapping("/commentAdd")
    @ResponseBody
    @RequireLogin
    public AjaxResult commentAdd(ViewpointComment comment, @LoginUser UserInfo userInfo){
        AjaxResult ajaxResult = new AjaxResult();
        try {
            if(userInfo != null) {
                comment.setUser(userInfo);
                viewpointCommentService.addComment(comment);
                //评论数量加1
                viewpointStatsCacheService.incrNum(comment.getViewpointId(),1,IViewpointStatsCacheService.VIEWPOINT_STATS_REPLYNUM);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.mark("评论失败");
            return ajaxResult;
        }
        return ajaxResult;
    }

    @Reference
    private IViewpointRefCommentService viewpointRefComment;

    // 前端传过来的参数  对应的景点评论id  内容content ， 类型 type ，回复的内容ObjectId refComment.id
    @RequestMapping("/refCommentAdd")
    @ResponseBody
//    @RequireLogin
    public AjaxResult refCommentAdd(ViewpointRefComment comment,Long viewpointId, @LoginUser UserInfo userInfo){
        AjaxResult ajaxResult = new AjaxResult();
        if(userInfo == null) {
            ajaxResult.mark("请先登录");
            ajaxResult.setCode(102);
            return ajaxResult;
        }
        comment.setUserId(userInfo.getId());
        comment.setUsername(userInfo.getNickname());
        comment.setHeadUrl(userInfo.getHeadImgUrl());
        ViewpointRefComment vrc = viewpointRefComment.commentRefAdd(comment);
        ajaxResult.setData(vrc);
        ajaxResult.setSuccess(true);
        //评论数量加1
        viewpointStatsCacheService.incrNum(viewpointId,1,IViewpointStatsCacheService.VIEWPOINT_STATS_REPLYNUM);
        return ajaxResult;
    }
    @Reference
    private IViewpointStatsCacheService viewpointStatsCacheService;
    //景点收藏
    @RequestMapping("/favor")
 //   @RequireLogin
    @ResponseBody
    private AjaxResult favor(Long viewId,@LoginUser UserInfo userInfo){
        AjaxResult result = new AjaxResult();
        //判断是否有登录,只有登录了才能点收藏
        if (userInfo == null){
            result.mark("请先登录");
            result.setCode(102);
            return result;
        }
        boolean flag = viewpointStatsCacheService.favor(viewId, userInfo.getId());
        result.setSuccess(flag);
        return result;
    }
    //去过
    @RequestMapping("/came")
  //  @RequireLogin
    @ResponseBody
    private AjaxResult came(Long viewId,@LoginUser UserInfo userInfo){
        AjaxResult result = new AjaxResult();
        //判断是否有登录,只有登录了才能点收藏
        if (userInfo == null){
            result.mark("请先登录");
            result.setCode(102);
            return result;
        }
        boolean flag = viewpointStatsCacheService.setCame(viewId, userInfo.getId());
        if(flag){
            result.setSuccess(flag);
        }else {
            result.mark("已经记录过了");
        }
        return result;
    }

    //thumbup
    @RequestMapping("/thumbup")
  //  @RequireLogin
    @ResponseBody
    private AjaxResult thumbup(Long viewCommentId,Long viewpointId,@LoginUser UserInfo userInfo){
        AjaxResult result = new AjaxResult();
        //判断是否有登录,只有登录了才能点收藏
        if (userInfo == null){
            result.mark("请先登录");
            result.setCode(102);
            return result;
        }
        result = viewpointStatsCacheService.thumbup(viewpointId ,viewCommentId, userInfo.getId());
        return result;
    }
}
